package com.feri.api.server;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;


/**
 * @author websocket服务
 */
@ServerEndpoint("/server/chat/{nickname}")//创建服务器的链接地址
@Component//IOC 创建对象
@Scope(scopeName = "prototype")//IOC创建对象方式为多例
public class WebSocketServer {
    //记录在线用户 key 用户昵称  value 会话对象 返回消息
    public static ConcurrentHashMap<String,Session> map=new ConcurrentHashMap<>();
    private String name;

//    创建链接
   @OnOpen
    public void open(Session session, @PathParam("nickname")String name){
//       判断昵称是否存在
       if (map.containsKey(name)){
//           存在返回
           try {
               session.getBasicRemote().sendText("亲！昵称已存在");
           } catch (IOException e) {
               e.printStackTrace();
           }
       }else {
//           添加在线用户
           map.put(name,session);
           this.name=name;
//           群发消息 欢迎语
           sendMsg("欢迎"+name+"进入宠物通");
       }

       System.err.println("新用户链接");
   }
//   接收消息
   @OnMessage
    public void msg(Session session,String msg){
       //   接收 转发消息
       sendMsg(name +"说："+msg);
       System.err.println("接受消息"+msg);
   }
//   出现错误
   @OnError
   public void err(Throwable throwable,Session session){
       System.err.println("系统故障"+throwable.getMessage());
   }
//   断开链接
   @OnClose

    public void cls(Session session){
       //   退出聊天
       map.remove(name);
       sendMsg(name+"退出了聊天");
       System.err.println("关闭");
   }

   public static void sendMsg(String msg){
       for (String h:map.keySet()){
           try {
               map.get(h).getBasicRemote().sendText(msg);
           } catch (IOException e) {
               e.printStackTrace();
           }

       }
   }
}